package com.sihai.ehr.web.action.salary;

import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;

import com.sihai.core.LimitedList;
import com.sihai.core.beans.BeanInject;
import com.sihai.ehr.model.biz.SalarySocialInsurance;
import com.sihai.ehr.model.biz.SalarySocialInsuranceDetail;
import com.sihai.ehr.model.sys.Organization;
import com.sihai.ehr.model.sys.SalaryInsurancePayEnum;
import com.sihai.ehr.model.sys.SalaryInsuranceTypeEnum;
import com.sihai.ehr.service.OrganizationService;
import com.sihai.ehr.service.SalaryInsuranceService;
import com.sihai.ehr.web.action.EHRAction;

/**
 * 薪资社保控制器
 * 
 * @author henry
 * 
 */
@Results({ @Result(name = "main", location = "salary_main.jsp"), 
		@Result(name = "insurance_manage", location = "insurance_manage.jsp"),
		@Result(name = "list", location = "insurance_manage_list.jsp") })
public class SalaryInsuranceAction extends EHRAction {
	/**
	 * 
	 */
	private static final long serialVersionUID = -8545909946931121325L;

	private Log log = LogFactory.getLog(SalaryInsuranceAction.class);
	@BeanInject
	private OrganizationService organizationService;

	@BeanInject
	private SalaryInsuranceService salaryInsuranceService;

	private List<Organization> organizations;
	private SalarySocialInsurance insurance;
	private LimitedList<SalarySocialInsurance> insurances;

	/** 社保方案编号 */
	private Long insuranceId;
	private String ids;
	
	// 个人项目数
	private int personalItemLength = 0;
	// 公司项目数
	private int companyItemLength = 0;

	@Action("/salary/insurance_main")
	@Override
	public String execute() throws Exception {
		listTitle = "社保管理";
		listAction = "/salary/insurance_list.xhtml";
		organizations = organizationService.findChildren(null, true, null, null);
		if (organizations != null && organizations.size() > 0) {
			if(getCurrentUserId() > 0){
            	Long topOrgId = getCurrentUser().getWork().getOrganization().getTopOrganization().getId();
            	Iterator<Organization> it = organizations.iterator();
            	while(it.hasNext()){
            		Organization o = it.next();
            		if(o.getId() != topOrgId){
            			it.remove();
            		}
            	}
            }
			organizationId = organizations.get(0).getId();
		}
		showChildOrg = false;
		return "main";
	}

	@Action("/salary/insurance_list")
	public String list() {
		listAction = "/salary/insurance_list.xhtml";
		insurances = salaryInsuranceService.find(organizationId, createLimit(), createSorter());
		paging(insurances);
		setPageUrl("salary/insurance_list.xhtml");
		return "list";
	}

	@Action("/salary/insurance_manage")
	public String dispatchInsurance() throws Exception {
		if (insuranceId == null || insuranceId < 0) { // 添加
			insurance = new SalarySocialInsurance();
			insurance.setOrganization(organizationService.get(organizationId));
		} else { // 修改
			insurance = salaryInsuranceService.get(insuranceId);
			if (insurance.getDetails() != null && insurance.getDetails().size() > 0) {
				for (Iterator iterator = insurance.getDetails().iterator(); iterator.hasNext();) {
					SalarySocialInsuranceDetail type = (SalarySocialInsuranceDetail) iterator.next();
					if (type.getProjectType() == SalaryInsurancePayEnum.personal) {
						personalItemLength ++;
					} else {
						companyItemLength ++;
					}

				}
			}
		}
		return "insurance_manage";
	}

	/**
	 * 保存社保管理
	 * 
	 * @return
	 * @throws Exception
	 */
	@Action("/salary/post_insurance")
	public String postInsurance() throws Exception {
		if (insurance == null) {
			if (log.isErrorEnabled()) {
				log.error("提交数据为空");
				return ERROR;
			}
		}

		if (insurance.getId() == null) {
			// 添加
		} else {
			// 修改
			/**
			 * 删除方案项目细节
			 */
			salaryInsuranceService.deleteSocialInsuranceDetails(insurance.getId());
		}
		Set<SalarySocialInsuranceDetail> details = new HashSet<SalarySocialInsuranceDetail>();
		// personal
		String[] insuranceTypePersonals = getParameterValues("insuranceType_personal");
		String[] projectTitlePersonals = getParameterValues("projectTitle_personal");
		String[] occupancyRatePersonals = getParameterValues("occupancyRate_personal");
		// company
		String[] insuranceTypeCompanys = getParameterValues("insuranceType_company");
		String[] projectTitleCompanys = getParameterValues("projectTitle_company");
		String[] occupancyRateCompanys = getParameterValues("occupancyRate_company");
		if (projectTitlePersonals != null && projectTitlePersonals.length > 0) {
			for (int i = 0; i < projectTitlePersonals.length; i++) {
				SalarySocialInsuranceDetail detail = new SalarySocialInsuranceDetail();
				detail.setInsuranceType(SalaryInsuranceTypeEnum.valueOf(insuranceTypePersonals[i]));
				detail.setProjectTitle(projectTitlePersonals[i]);
				detail.setOccupancyRate(Float.parseFloat(occupancyRatePersonals[i]));
				detail.setProjectType(SalaryInsurancePayEnum.personal);
				insurance.addDetailItem(detail);
			}
		}

		if (projectTitleCompanys != null && projectTitleCompanys.length > 0) {
			for (int i = 0; i < projectTitleCompanys.length; i++) {
				SalarySocialInsuranceDetail detail = new SalarySocialInsuranceDetail();
				detail.setInsuranceType(SalaryInsuranceTypeEnum.valueOf(insuranceTypeCompanys[i]));
				detail.setProjectTitle(projectTitleCompanys[i]);
				detail.setOccupancyRate(Float.parseFloat(occupancyRateCompanys[i]));
				detail.setProjectType(SalaryInsurancePayEnum.company);
				insurance.addDetailItem(detail);
			}
		}
		// 保存数据
		try {
			salaryInsuranceService.save(insurance);
		} catch (Exception e) {
			log.equals(e.getMessage());
			return ERROR;
		}
		return "main";
	}

	/**
	 * 删除社保方案
	 * 
	 * @return
	 * @throws Exception
	 */
	@Action(value = "/salary/insurance_delete", results = { @Result(name = "success", type = "plainText") })
	public String deleteInsurance() throws Exception {
		if (StringUtils.isNotBlank(ids)) {
			try {
				salaryInsuranceService.deleteSocialInsurances(ids);
			} catch (Exception e) {
				if (log.isErrorEnabled()) {
					log.error(e.getMessage());
				}
				return ERROR;
			}

		}

		return SUCCESS;
	}

	public List<Organization> getOrganizations() {
		return organizations;
	}

	public void setOrganizations(List<Organization> organizations) {
		this.organizations = organizations;
	}

	public SalarySocialInsurance getInsurance() {
		return insurance;
	}

	public void setInsurance(SalarySocialInsurance insurance) {
		this.insurance = insurance;
	}

	public LimitedList<SalarySocialInsurance> getInsurances() {
		return insurances;
	}

	public void setInsurances(LimitedList<SalarySocialInsurance> insurances) {
		this.insurances = insurances;
	}

	public Long getInsuranceId() {
		return insuranceId;
	}

	public void setInsuranceId(Long insuranceId) {
		this.insuranceId = insuranceId;
	}

	public String getIds() {
		return ids;
	}

	public void setIds(String ids) {
		this.ids = ids;
	}
	
	public int getPersonalItemLength() {
		return personalItemLength;
	}
	
	public void setPersonalItemLength(int personalItemLength) {
		this.personalItemLength = personalItemLength;
	}
	
	public int getCompanyItemLength() {
		return companyItemLength;
	}
	
	public void setCompanyItemLength(int companyItemLength) {
		this.companyItemLength = companyItemLength;
	}
}
